<script setup>
import { ref, computed } from 'vue'

// 定义父组件传来的参数
const props = defineProps({
  limit: { //每页显示条数
    type: Number,
    default: 20,
    required: true
  },
  total: { //总条数
    type: Number,
    default: 0,
    required: true
  },
  page: { //总条数
    type: Number,
    default: 0,
    required: true
  }
})

// 定义父组件调用子组件的方法
const emits = defineEmits(['turn'])

const curPage = ref(props.page || 1)
const offset = ref(0)

// allPage 根据总条数和每页显示条数计算总页数
const allPage = computed(() => {
  return Math.ceil(props.total / props.limit)
})

// pageNum 计算每页显示页面码数
const pageNum = computed(() =>  {
  let pn = allPage.value, cur = curPage.value, numArr = []
  if(pn <= 9) {
    for(let i = 1; i <= pn; i++) {
      numArr.push(i)
    }
  } else if(cur < 10) {
    for(let i = 1; i <= 10; i++) {
      numArr.push(i)
    }
  } else if(cur > pn - 9) {
    for(let i = pn-9; i <= pn; i++) {
      numArr.push(i)
    }
  } else {
    for(let i = -4; i <= 5; i++) {
      numArr.push(cur+i)
    }
  }
  return numArr
})

// chgNum 翻页，显示条数变化
const chgNum = (cur) => {
  if (cur < 1) {
    curPage.value = 1
  } else if (cur > allPage.value) {
    curPage.value = allPage.value
  } else {
    curPage.value = cur
    offset.value = (cur - 1) * props.limit
  }
  emits('turn', offset.value, curPage.value)
}
</script>

<template>
  <div v-if="allPage>1" class="pg-a">
    <div class="pg-b">每页 {{limit}} 条 共 {{total}} 条</div>
    <div v-if="curPage!==1" class="pg-b">
      <span class="pg-d" @click="chgNum(1)">首页</span>
      <span class="pg-d" @click="chgNum(curPage-1)">上一页</span>
    </div>
    <div class="pg-b">
      <span v-for="per in pageNum" :class="[curPage===per ? 'pg-c' : 'pg-d']" @click="chgNum(per)">{{per}}</span>
    </div>
    <div v-if="curPage!==allPage" class="pg-b">
      <span class="pg-d" @click="chgNum(curPage+1)">下一页</span>
      <span class="pg-d" @click="chgNum(allPage)">尾页</span>
    </div>
    <div class="pg-b">第 {{curPage}} / {{allPage}} 页</div>
  </div>
</template>

<style scoped>
.pg-a {padding: 10px 0; text-align: center; display: flex; display: -webkit-flex; justify-content: center;}
.pg-b {line-height: 40px;}
.pg-c {background-color: #409eff; color: #FFF; border: 1px solid #409eff; padding: 3px 7px; margin: 0 5px; border-radius: 4px; cursor: pointer;}
.pg-d {background-color: #ecf5ff; color: #409eff; border: 1px solid #409eff; padding: 3px 7px; margin: 0 5px; border-radius: 4px; cursor: pointer;}
.pg-d:hover {background-color: #409eff; border: 1px solid #409eff; color: #FFF;}
</style>
